package com.hiv.service;

import java.util.List;
import java.util.Optional;

import cn.hutool.core.convert.Convert;
import com.hiv.common.PageInfo;
import com.hiv.common.enums.AccountTypeEnum;
import com.hiv.common.enums.ErrorCode;
import com.hiv.common.exception.BusinessException;
import com.hiv.common.helper.AccountHelper;
import com.hiv.common.param.page.PageQueryHospitalParam;
import com.hiv.common.utils.AssertUtil;
import com.hiv.mapper.domain.Admin;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.hiv.mapper.HospitalMapper;
import com.hiv.mapper.domain.Hospital;
import org.springframework.transaction.annotation.Transactional;

/**
 * 质控中心/医院/检验所Service业务层处理
 * 
 * @author zhanghong
 * @date 2022-09-18
 */
@Service
public class HospitalService {
    @Autowired
    private HospitalMapper hospitalMapper;
    @Autowired
    private AccountHelper accountHelper;

    /**
     * 分页查询
     * @param param
     * @return
     */
    public PageInfo<Hospital> pageQuery(Admin admin, PageQueryHospitalParam param) {
        if (AccountTypeEnum.isQualityControlCenterAdmin(admin)) {
            param.setParentId(admin.getHospitalId());
        }
        long count = hospitalMapper.pageCount(param);
        List<Hospital> list = hospitalMapper.pageQuery(param, param.getPageSize(), param.fetchOffSet());
        for (Hospital item : list) {
            if (item.getParentId() != null) {
                item.setParentName(getHospitalName(item.getParentId()));
            }
        }
        return new PageInfo<>(param.getPageNum(), param.getPageSize(), list, count);
    }

    /**
     * 查询医院
     * 
     * @param id 医院主键
     * @return 医院
     */
    public Hospital getById(Long id) {
        return hospitalMapper.selectById(id);
    }

    /**
     * 查询医院列表
     * 
     * @param hospital 医院
     * @return 医院
     */
    public List<Hospital> selectList(Hospital hospital) {
        return hospitalMapper.selectList(hospital);
    }

    /**
     * 保存医院
     *
     * @param hospital 医院
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(Hospital hospital) {
        try {
            if (hospital.getId() != null) {
                hospitalMapper.update(hospital);
                return true;
            }
            hospitalMapper.insert(hospital);
        } catch (DuplicateKeyException ex) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "名称已存在");
        }
        return true;
    }

    /**
     * 启用/停用
     *
     * @param hospital 医院
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(Hospital hospital) {
        try {
            Hospital db = hospitalMapper.selectById(hospital.getId());
            if (db.getLevel() == 1) {
                if (hospital.getStatus() == 1) {
                    //启用当前一级下的所有
                    hospitalMapper.updateStatusByParentId(1, hospital.getId());
                } else if (hospital.getStatus() == 0) {
                    //停用当前一级下的所有
                    hospitalMapper.updateStatusByParentId(0, hospital.getId());
                }
            } else {
                if (hospital.getStatus() == 1) {
                    //将父级也一起启用
                    hospitalMapper.updateStatusById(1, db.getParentId());
                } else if (hospital.getStatus() == 0) {
                    List<Hospital> hospitals = hospitalMapper.queryEnableBroByParentId(db.getParentId());
                    if (CollectionUtils.isNotEmpty(hospitals) && hospitals.size() == 1 && hospitals.get(0).getId().equals(db.getId())) {
                        //将父级也一起停用
                        hospitalMapper.updateStatusById(0, db.getParentId());
                    }
                }
            }
            hospitalMapper.update(hospital);
        } catch (DuplicateKeyException ex) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "名称已存在");
        }
        return true;
    }

    /**
     * 批量删除医院
     * 
     * @param ids 需要删除的医院主键
     * @return 结果
     */
    public Boolean deleteByIds(String ids) {
        //删除校验
        String[] idsArr = Convert.toStrArray(ids);
        for (String id : idsArr) {
            List<Hospital> hospitals = hospitalMapper.listByParentId(Long.parseLong(id));
            AssertUtil.assertEmpty(hospitals, "有关联医院，删除失败");
        }
        hospitalMapper.deleteByIds(idsArr);
        return true;
    }

    /**
     * 树形医院质控中心查询
     * @return
     */
    public List<Hospital> tree(Hospital param) {
        AssertUtil.assertNotNull(param.getType(), "类型不能为空");
        param.setStatus(1);
        if (param.getType() == 2) {
            Hospital jiGouHospitalParam = new Hospital();
            jiGouHospitalParam.setType(1);
            jiGouHospitalParam.setStatus(1);
            List<Hospital> jiGouHospitalList = hospitalMapper.selectList(jiGouHospitalParam);
            for (Hospital item : jiGouHospitalList) {
                List<Hospital> hospitals = hospitalMapper.listTreeByParentId(item.getId());
                if (CollectionUtils.isNotEmpty(hospitals)) {
                    item.setChildren(hospitals);
                }
            }
            return jiGouHospitalList;
        }
        return hospitalMapper.selectList(param);
    }

    public String getHospitalName(Long hospitalId) {
        if (hospitalId == null) {
            return null;
        }
        Hospital hospital = hospitalMapper.selectById(hospitalId);
        return Optional.ofNullable(hospital).map(Hospital::getName).orElse(null);
    }
}
